package main

import (
	"log"
	"net/http"
	"os"
	"strings"
)

func main() {
	http.HandleFunc("/", resHeader)
	http.HandleFunc("/healthz", healthz)
	err := http.ListenAndServe(":8000",nil)
	if err != nil{
		log.Println("Failed to start http server",err.Error())
	}
}

func resHeader(w http.ResponseWriter,r *http.Request)  {

	// 1. write request header
	reqHeaderMap := map[string][]string (r.Header)
	for k,_ := range reqHeaderMap{
		reqHeaderValue := r.Header.Get(k)
		w.Header().Set(k,reqHeaderValue)
	}

	//2. get os env
	VERKEY := "VERSION"
	ver := os.Getenv(VERKEY)
	w.Header().Set(VERKEY,ver)

	//3. record the information using logs

	//response
	w.WriteHeader(http.StatusOK)
	_, err := w.Write([]byte("Welcome to my website!\n"))
	if err != nil{
		log.Println("resHeader: Write response body failed,",err.Error())
	}
	// get client ip
	f := func(c rune) bool {
		if c == ':' {
			return true
		} else {
			return false
		}
	}
	clientInfo := strings.FieldsFunc(r.RemoteAddr, f)
	clientIp := clientInfo[0]
	log.Print("Client is visiting /, Client ip is:", clientIp)
	log.Println("HTTP response code is", http.StatusOK)
}

func healthz(w http.ResponseWriter,r *http.Request)  {
	//response
	w.WriteHeader(http.StatusOK)
	_, err := w.Write([]byte("200\n"))
	if err != nil{
		log.Println("healthz: Write response body failed,",err.Error())
	}

}

